package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.IOrderDetailService;
import com.itheima.reggie.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <b><code>OrdersServiceImpl</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 29/06/2024 20:48.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@Service("ordersService")
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders 订单信息
     * @return 是否成功
     */
    @Override
    public R<String> submit(Orders orders) {
        // 获取当前用户id
        Long userId = BaseContext.getCurrentUser();
        // 查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(shoppingCartQueryWrapper);

        long orderId = IdWorker.getId();
        // 订单明细
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount().multiply(new BigDecimal(item.getNumber())));
            return orderDetail;
        }).collect(Collectors.toList());

        // 金额
        BigDecimal amount = orderDetails.stream().map(item -> item.getAmount()).reduce(new BigDecimal(0), (a, b) -> a.add(b));

        // 查询用户数据
        User user = userMapper.selectById(userId);
        // 查询地址数据
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        // 向订单表插入一条数据

        orders.setNumber(String.valueOf(orderId));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(amount);    // 订单金额
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress("写死一个地址");
        this.save(orders);
        // 向订单明细表插入n条数据
        orderDetailService.saveBatch(orderDetails);
        // 下单完成后清空购物车数据
        shoppingCartMapper.delete(shoppingCartQueryWrapper);
        return R.success("下单成功");
    }

    /**
     * 查看订单
     * @param page 当前页
     * @param pageSize 每页显示条数
     * @return 分页信息
     */
    @Override
    public R<Page<Orders>> userPage(int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Long currentUser = BaseContext.getCurrentUser();
        Page<Orders> pageInfo = baseMapper.selectPage(ordersPage, new LambdaQueryWrapper<Orders>().eq(Orders::getUserId, currentUser));
        return R.success(pageInfo);
    }
}
